package com.ruoyi.web.cp.service.rm;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.web.core.config.ConfigLoader;
import com.ruoyi.web.cp.domain.rm.RmGame;
import com.ruoyi.web.cp.domain.rm.RmResult;
import com.ruoyi.web.cp.domain.rm.RmobMerge;
import com.ruoyi.web.cp.domain.rm.RmobMergeExcel;
import com.ruoyi.web.cp.service.WinxinService;
import com.ruoyi.web.mapper.RmobMergeMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xiesm
 * @Description: TODO
 * @date 2025-07-21 16:39
 */
@Slf4j
@Service
public class RmobResultMergeService {
    @Autowired
    private RmobMergeMapper rmobMergeMapper;
    @Autowired
    private RmGameService rmGameService;
    @Autowired
    private WinxinService winxinService;
    @Autowired
    private RmResultDoubleMergeService rmResultDoubleMergeService;
    @Autowired
    private ConfigLoader configLoader;

    @SneakyThrows
    public void merge(String tableName, boolean isHalf, String name) {
        try {
            Date beginDate = DateUtil.offsetHour(new Date(), -24);
            List<RmobMerge> rmobMergeList = getRmobDoubleMergeList(beginDate, null, tableName);
            if (CollUtil.isEmpty(rmobMergeList)) {
                return;
            }
            List<String> gameIds = rmobMergeList.stream().map(RmobMerge::getGameId)
                    .distinct()
                    .collect(Collectors.toList());

            List<RmResult> rmResultList = rmResultDoubleMergeService.getResultsByGameIds(gameIds);
            // 生成 gameId -> allScore 的字典
            Map<String, RmResult> gameIdToRmResultMap = rmResultList.stream()
                    .collect(Collectors.toMap(
                            RmResult::getGameId,
                            v -> v,
                            (existing, replacement) -> existing
                    ));

            List<RmGame> rmGames = rmGameService.getGamesByGameIds(gameIds);
            Map<String, RmGame> gameIdToRmGameMap = rmGames.stream()
                    .collect(Collectors.toMap(
                            RmGame::getGameId, v -> v,
                            (existing, replacement) -> existing
                    ));

            // 后续可以使用该字典进行匹配、更新等操作
            // 例如：遍历 rmobDoubleMergeList 并关联 allScore
            List<RmobMergeExcel> datas = new ArrayList<>();
            for (RmobMerge merge : rmobMergeList) {
                String gameId = merge.getGameId();
                RmGame rmGame = gameIdToRmGameMap.get(gameId);
                if (rmGame == null) {
                    continue;
                }
                RmobMergeExcel data = new RmobMergeExcel(rmGame.getTeamA(), rmGame.getTeamB(), rmGame.getLeague(),
                        rmGame.getDate());
                datas.add(data);

                //全场、半场比分
                RmResult rmResult = gameIdToRmResultMap.get(merge.getGameId());
                if (rmResult != null) {
                    data.setAllScore(rmResult.getAllScore());
                    data.setHalfScore(rmResult.getHalfScore());
                }

                //比赛详情
                JSONArray array = merge.getDetailsJsonToJSON();
                List<RmobMergeExcel.Detail> details = new ArrayList<>();
                data.setDetails(details);
                for (int i = 0; i < array.size(); i++) {
                    JSONObject json = array.getJSONObject(i);
                    RmobMergeExcel.Detail detail = new RmobMergeExcel.Detail(data, json.getString("score"), json.getString("rm_plv"),
                            json.getString("ob_plv"), json.getString("fit"), isHalf);
                    details.add(detail);
                }
            }

            String path = configLoader.getRmPath() + name + ".xlsx";
            File tempFile = new File(path);
            // 如果文件已存在，先删除
            if (tempFile.exists()) {
                FileUtil.del(tempFile);
            }
            // 导出到 Excel
            exportRmobDoubleMergeToExcel(datas, tempFile, isHalf);
            winxinService.uploadMediaByAppAndSendMsg("1000009", path);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public List<RmobMerge> getRmobDoubleMergeList(Date beginDate, Date endDate, String tableName) {
        return rmobMergeMapper.selectByGameIdAndDateRangeTable(null, beginDate, endDate, tableName);
    }

    public void exportRmobDoubleMergeToExcel(List<RmobMergeExcel> rmobMergeExcelList, File tempFile, boolean isHalf) {
        // 创建 ExcelWriter 对象
        ExcelWriter writer = ExcelUtil.getWriter(tempFile);

        // 手动设置表头
        String[] headers = {"日期", "联赛", "主队", "客队", "半场结果", "全场结果"};
        writer.writeHeadRow(Arrays.asList(headers));

        // 写入数据（假设 RmobDoubleMerge 有对应的 getter 方法）
        for (RmobMergeExcel item : rmobMergeExcelList) {
            if (item.getDetails() == null) {
                continue;
            }

            writer.writeRow(Arrays.asList(
                    item.getDateStr(),            // 日期
                    item.getLeague(),          // 联赛
                    item.getTeamA(),           // 主队
                    item.getTeamB(),           // 客队
                    item.getHalfScore(),          // 半场结果
                    item.getAllScore()          //  全场结果
            ));

            List<RmobMergeExcel.Detail> details = item.getDetails();
            if (CollUtil.isEmpty(details)) {
                continue;
            }
            for (RmobMergeExcel.Detail detail : details) {
                writer.writeRow(Arrays.asList(
                        "",
                        detail.getScore(),
                        detail.getRm_plv(),
                        detail.getOb_plv(),
                        isHalf ? detail.getRedBlack() : "",
                        isHalf ? "" : detail.getRedBlack()
                ));
            }
        }
        int[] columnWidths = {
                18 * 256, // 日期
                15 * 256, // 联赛
                20 * 256, // 主队
                20 * 256, // 客队
                12 * 256,  // 半场结果
                12 * 256   // 全场结果
        };

        for (int i = 0; i < columnWidths.length; i++) {
            writer.getSheet().setColumnWidth(i, columnWidths[i]);
        }
        // 关闭流
        writer.close();
    }
}
